//
//  SISSChooseCityViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/9/12.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSChooseCityViewController.h"
#import <BMKLocationKit/BMKLocationComponent.h>
#import "SISSBaseView.h"
#import "SISSChooseCityLocationCell.h"

@interface SISSChooseCityViewController ()<BMKLocationAuthDelegate,BMKLocationManagerDelegate,SISSChooseCityLocationCellDelegate>

/// <#Annotation#>
@property (strong, nonatomic) BMKLocationManager *locationManager;

@property (strong,nonatomic) NSMutableArray *groupDataArray;
@property (strong,nonatomic) NSMutableArray *groupTitleArray;
@property (weak, nonatomic) SISSChooseCityLocationCell *animateCell;

@end

@implementation SISSChooseCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
     [self handleDataArray:@[@"深圳", @"上海", @"北京", @"广州", @"成都", @"昆明"] GroupDataArray:self.groupDataArray GroupTitleArray:self.groupTitleArray];
    
    [[BMKLocationAuth sharedInstance] checkPermisionWithKey:BMKMAP_KEY authDelegate:self];
    
    //初始化实例
    _locationManager = [[BMKLocationManager alloc] init];
    //设置delegate
    _locationManager.delegate = self;
    //设置返回位置的坐标系类型
    _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
    //设置距离过滤参数
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    //设置预期精度参数
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置应用位置类型
    _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
    //设置是否自动停止位置更新
    _locationManager.pausesLocationUpdatesAutomatically = NO;
    //设置是否允许后台定位
    //_locationManager.allowsBackgroundLocationUpdates = YES;
    //设置位置获取超时时间
    _locationManager.locationTimeout = 10;
    //设置获取地址信息超时时间
    _locationManager.reGeocodeTimeout = 10;
    
    [self.groupDataArray replaceObjectAtIndex:0 withObject:@[@"定位中"]];
    [_locationManager requestLocationWithReGeocode:YES withNetworkState:YES completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
        if (error) {
            [self.groupDataArray replaceObjectAtIndex:0 withObject:@[@"定位失败"]];
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            [self.tableView reloadData];
        }
        if (location) {//得到定位信息，添加annotation
            
            if (location.location) {
                NSLog(@"LOC = %@",location.location);
            }
            if (location.rgcData) {
                NSLog(@"rgc = %@",[location.rgcData description]);
                
                [self.groupDataArray replaceObjectAtIndex:0 withObject:@[location.rgcData.city]];
                [self.tableView reloadData];
                
            }
        }
        NSLog(@"netstate = %d",state);
    }];
    
    self.dataSource = @[@{@"section":@"当前定位",
                          @"list":@[@""]
                          },
                        @{@"section":@"热门城市",
                          @"list":@[@"深圳", @"上海", @"北京"]
                          }];
    
   
    
}

#pragma mark - SISSChooseCityLocationCellDelegate
- (void)locationButtonClickedAction {
    NSLog(@"点击定位");
    [self.groupDataArray replaceObjectAtIndex:0 withObject:@[@"定位中"]];
    [self.tableView reloadData];
    [_locationManager requestLocationWithReGeocode:YES withNetworkState:YES completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
        if (error) {
            [self.groupDataArray replaceObjectAtIndex:0 withObject:@[@"定位失败"]];
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            [self.tableView reloadData];
        }
        if (location) {//得到定位信息，添加annotation
            
            if (location.location) {
                NSLog(@"LOC = %@",location.location);
            }
            if (location.rgcData) {
                NSLog(@"rgc = %@",[location.rgcData description]);
            
                [self.groupDataArray replaceObjectAtIndex:0 withObject:@[location.rgcData.city]];
                [self.tableView reloadData];
                
            }
        }
        NSLog(@"netstate = %d",state);
    }];
//    [self.animateCell startRotate];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.groupTitleArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    NSDictionary *sectionDict = self.dataSource[section];
//    NSArray *sectionArr = sectionDict[@"list"];
    return [self.groupDataArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        SISSChooseCityLocationCell *cell = [tableView dequeueReusableCellWithIdentifier:chooseCityLocationCellReuseID forIndexPath:indexPath];
        NSArray *arr = self.groupDataArray[indexPath.section];
        NSString *title = arr[indexPath.row];
        cell.titleStr = arr[indexPath.row];
        cell.delegate = self;
        self.animateCell = cell;
        if ([title isEqualToString:@"定位中"] || [title isEqualToString:@"定位当前城市"]) {
            [cell startRotate];
        } else {
            [cell endRotate];
        }
        return cell;
    } else {
        
        static NSString *reuseID = @"ID";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
        if ( !cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseID];
            
            UIView *lineView = [[UIView alloc] init];
            lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            [cell.contentView addSubview:lineView];
            
            [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.bottom.equalTo(cell.contentView);
                make.right.equalTo(cell.contentView).offset(32);
                make.height.mas_equalTo(1);
            }];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = [UIFont systemFontOfSize:17];
        cell.textLabel.textColor = MAIN_TEXT_COLOR;
        //    NSDictionary *sectionDict = self.dataSource[indexPath.section];
        //    NSArray *sectionArr = sectionDict[@"list"];
        //    cell.textLabel.text = sectionArr[indexPath.row];
        NSArray *arr = self.groupDataArray[indexPath.section];
        cell.textLabel.text = arr[indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        return cell;
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return 54;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.selectCompleteBlock) {
//        NSDictionary *sectionDict = self.dataSource[indexPath.section];
//        NSArray *sectionArr = sectionDict[@"list"];
        NSArray *sectionArr = self.groupDataArray[indexPath.section];
        self.selectCompleteBlock(sectionArr[indexPath.row]);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSDictionary *sectionDict = self.dataSource[section];
    return sectionDict[@"section"];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SISSBaseView *headerView = [[SISSBaseView alloc] init];
    headerView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    UILabel *label = [[UILabel alloc] init];
    label.textColor = COLOR(0x334A60);
    label.font = [UIFont systemFontOfSize:16];
    [headerView addSubview:label];
    
    CGFloat margin = 8.0;
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerView).offset(2 * margin);
        make.centerY.equalTo(headerView);
    }];
//    NSDictionary *sectionDict = self.dataSource[section];
    NSString * title = self.groupTitleArray[section];
//    label.text = sectionDict[@"section"];
    label.text = title;
    
    return headerView;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.groupTitleArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return index;
}

- (NSString *)transform:(NSString *)chinese {
    NSMutableString *pinyin = [chinese mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    //NSLog(@"%@", pinyin);
    return [pinyin uppercaseString];
}
//按首字母分组
- (void)handleDataArray:(NSArray*)dataArray GroupDataArray:(NSMutableArray*)groupDataArray GroupTitleArray:(NSMutableArray*)groupTitleArray {
    
    NSMutableArray * groupCurrentDataArray = nil;
    NSString * lastFirstLetter = nil;
    NSString * currentFirstLetter = nil;
    dataArray = [dataArray sortedArrayUsingComparator:^NSComparisonResult(NSString* obj1, NSString* obj2) {
        NSString * obj1FirstLetter = [[self transform:obj1] substringToIndex:1];
        NSString * obj2FirstLetter = [[self transform:obj2] substringToIndex:1];
        return [obj1FirstLetter compare:obj2FirstLetter];
    }];
    for(NSString * name in dataArray){
        currentFirstLetter = [[self transform:name] substringToIndex:1];
        if(![lastFirstLetter isEqualToString:currentFirstLetter]){
            groupCurrentDataArray = [[NSMutableArray alloc] init];
            [groupTitleArray addObject:currentFirstLetter];
            [groupDataArray addObject:groupCurrentDataArray];
        }
        [groupCurrentDataArray addObject:name];
        lastFirstLetter = currentFirstLetter;
    }
//    if([[groupTitleArray firstObject] isEqualToString:@"#"]){
//        id groupTile = [groupTitleArray firstObject];
//        [groupTitleArray removeObject:groupTile];
//        [groupTitleArray addObject:groupTile];
//
//        id dataValue = [groupTitleArray firstObject];
//        [groupTitleArray removeObject:dataValue];
//        [groupTitleArray addObject:dataValue];
//    }
}

#pragma mark - UI
- (void)setupSubviews {
    [super setupSubviews];
    
    [self.tableView registerClass:[SISSChooseCityLocationCell class] forCellReuseIdentifier:chooseCityLocationCellReuseID];
}

-(NSMutableArray *)groupDataArray{
    if(!_groupDataArray){
        _groupDataArray = [[NSMutableArray alloc] initWithArray:@[@[@"定位当前城市"],@[@"深圳",@"上海"]]];
    }
    return _groupDataArray;
}
-(NSMutableArray *)groupTitleArray{
    if(!_groupTitleArray){
        _groupTitleArray = [[NSMutableArray alloc] initWithArray:@[@"#",@"热"]];
    }
    return _groupTitleArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
